#!/usr/bin/env python3
"""
针对 8.140.59.178 的专用部署脚本
"""

import subprocess
import sys
import time
from datetime import datetime

def run_command(command, timeout=300):
    """执行命令"""
    try:
        print(f"执行: {command}")
        result = subprocess.run(
            command, 
            shell=True, 
            capture_output=True, 
            text=True, 
            timeout=timeout,
            encoding='utf-8'
        )
        
        if result.returncode == 0:
            print(f"✅ 成功")
            return result.stdout.strip()
        else:
            print(f"❌ 失败: {result.stderr}")
            return None
    except subprocess.TimeoutExpired:
        print(f"❌ 超时")
        return None
    except Exception as e:
        print(f"❌ 异常: {str(e)}")
        return None

def deploy_to_server():
    """部署到 8.140.59.178"""
    server_ip = "8.140.59.178"
    
    print("=" * 60)
    print(f"  部署到阿里云ECS: {server_ip}")
    print("=" * 60)
    print()
    
    # 步骤1: 测试SSH连接
    print("步骤1: 测试SSH连接...")
    ssh_test = run_command(
        f'ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no root@{server_ip} "echo \'SSH OK\'"',
        timeout=15
    )
    
    if not ssh_test or "SSH OK" not in ssh_test:
        print("❌ SSH连接失败")
        print("\n请检查:")
        print("1. ECS实例状态是否为 '运行中'")
        print("2. 安全组是否开放22端口")
        print("3. root密码是否正确")
        return False
    
    print("✅ SSH连接成功")
    
    # 步骤2: 创建目录并上传文件
    print("\n步骤2: 创建目录并上传文件...")
    
    # 创建目录
    if not run_command(f'ssh root@{server_ip} "mkdir -p /root/cross_network_server"'):
        print("❌ 创建目录失败")
        return False
    
    # 上传文件
    files = [
        ("cross_network_server.py", "/root/cross_network_server/cross_network_server.py"),
        ("deploy_cross_network_server.sh", "/root/cross_network_server/deploy_cross_network_server.sh")
    ]
    
    for local_file, remote_path in files:
        if not run_command(f'scp "{local_file}" root@{server_ip}:"{remote_path}"'):
            print(f"❌ 上传文件失败: {local_file}")
            return False
    
    # 创建requirements.txt
    requirements = "websockets==11.0.3\nasynci"
    if not run_command(f'ssh root@{server_ip} "echo \'{requirements}\' > /root/cross_network_server/requirements.txt"'):
        print("❌ 创建requirements.txt失败")
        return False
    
    print("✅ 文件上传完成")
    
    # 步骤3: 执行部署脚本
    print("\n步骤3: 执行部署脚本...")
    deploy_command = (
        f'ssh root@{server_ip} "'
        f'cd /root/cross_network_server && '
        f'chmod +x deploy_cross_network_server.sh && '
        f'bash deploy_cross_network_server.sh"'
    )
    
    if not run_command(deploy_command, timeout=600):
        print("❌ 部署脚本执行失败")
        return False
    
    print("✅ 部署脚本执行完成")
    
    # 步骤4: 验证部署
    print("\n步骤4: 验证部署...")
    
    # 检查服务状态
    service_status = run_command(
        f'ssh root@{server_ip} "systemctl is-active cross-network-server.service"'
    )
    
    if service_status and "active" in service_status:
        print("✅ 服务运行正常")
    else:
        print(f"⚠️ 服务状态: {service_status}")
    
    # 检查端口
    port_check = run_command(
        f'ssh root@{server_ip} "netstat -tlnp | grep :8085"'
    )
    
    if port_check:
        print("✅ 端口8085监听正常")
    else:
        print("⚠️ 端口8085未监听")
    
    return True

def main():
    print("跨网络数据传输服务器 - 专用部署工具")
    print("目标服务器: 8.140.59.178:8085")
    print()
    
    if deploy_to_server():
        print("\n" + "=" * 60)
        print("         🎉 部署完成！")
        print("=" * 60)
        print()
        print("服务器信息:")
        print("- IP地址: 8.140.59.178")
        print("- WebSocket: ws://8.140.59.178:8085")
        print("- 服务名: cross-network-server.service")
        print()
        print("Android应用配置:")
        print("你的ServerConfig.kt已经配置了这个服务器地址")
        print("重新编译APK即可使用:")
        print("  .\\gradlew assembleRelease")
        print()
        print("管理命令:")
        print("- 查看状态: ssh root@8.140.59.178 'systemctl status cross-network-server.service'")
        print("- 查看日志: ssh root@8.140.59.178 'journalctl -u cross-network-server.service -f'")
        print("- 重启服务: ssh root@8.140.59.178 'systemctl restart cross-network-server.service'")
    else:
        print("\n❌ 部署失败")
        print("请检查上面的错误信息并手动排查")

if __name__ == "__main__":
    main()